package com.tcsl.exercise.demo.controller;

import com.tcsl.exercise.demo.constants.ResultEnum;
import com.tcsl.exercise.demo.entity.ItemEntity;
import com.tcsl.exercise.demo.entity.ItemSizeCa;
import com.tcsl.exercise.demo.entity.Page;
import com.tcsl.exercise.demo.entity.R;
import com.tcsl.exercise.demo.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class CrudController {
    @Autowired
    ItemService itemService;

    /**
     * 分页查询，模糊查询
     * @param currentPage  当前页
     * @param pageSize  页面显示的数量
     * @param keyWord   搜索关键字
     * @return  查询的品项实例list
     */
    @RequestMapping("/test")
    public R selectByPage(Integer currentPage,Integer pageSize,String keyWord){
        //System.out.println(currentPage+"____"+pageSize+"___"+keyWord);
        List<ItemEntity> data = itemService.selectOne(currentPage,pageSize,keyWord);
        int count = itemService.selectItemCount(keyWord);
        if (data != null && data.size() != 0){
            Page<ItemEntity> page = new Page<>();
            page.setTotalCount(count);
            page.setPageSize(pageSize);
            page.setCurrentPage(currentPage);
            page.setDataList(data);
            return R.ok().setData(page);
        }
        return R.nodata();
    }

    /**
     * 查询全部规格进行回显
     * @return
     */
    @RequestMapping("/getItemCa")
    public R getAllItemSizeCa(){
        List<ItemSizeCa> data = itemService.selectItemCa();
        return R.ok().setData(data);
    }

    /**
     * 新建品项
     * @param itemEntity  品项的各项参数
     * @return
     */
    @RequestMapping("/addItem")
    public R addItem(@Validated ItemEntity itemEntity){

        ResultEnum resultEnum = itemService.addItem(itemEntity);
        if (ResultEnum.SUCCESS.getCode() != resultEnum.getCode()){
            return R.err().setMsg(resultEnum.getMsg());
        }
        return R.ok();
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @RequestMapping("/deleteItemById")
    public R delete(Long id){
        //System.out.println(id);
        itemService.deleteById(id);
        return R.ok();

    }

    /**
     * 编辑
     * @param itemEntity
     * @return
     */
    @RequestMapping("/editItem")
    public R editItemById(@Validated ItemEntity itemEntity){
        ResultEnum resultEnum = itemService.editItemById(itemEntity);
        if (ResultEnum.SUCCESS.getCode() == resultEnum.getCode()){
            return R.ok();
        }
        return R.err().setMsg(resultEnum.getMsg());
    }
}
